﻿using MySql.Data.MySqlClient;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WareHouse.Domain;
using WareHouse.Domain.Finances;
using WareHouse.Domain.ModelClass;
using WareHouse.Domain.Procurements;
using WareHouse.Domain.Warehouses;

namespace WareHouse.DB.AllDbContext
{
    /// <summary>
    /// sqlsugar上下文类
    /// </summary>
    public class SqlSugarDbContext
    {
        public SqlSugarClient Db;

        public SqlSugarDbContext()
        {
            using(var connection = new MySqlConnection())
            {
                //执行数据库操作
                Db = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = "server=10.31.52.16;database=WmsDB;uid=root;pwd=123456",
                    DbType = DbType.MySql, //数据库类型使用MySQL
                    InitKeyType = InitKeyType.Attribute, //InitKeyType 属性设置为Attribute，表示使用实体类上的特性标记配置表结构
                    IsAutoCloseConnection = true, //是否自动释放连接，默认为false
                });

                Db.Aop.OnLogExecuting = (sql, pars) =>
                {

                    //获取原生SQL推荐 5.1.4.63  性能OK
                    Console.WriteLine(UtilMethods.GetNativeSql(sql, pars));
                    //获取无参数化SQL 对性能有影响，特别大的SQL参数多的，调试使用
                    //Console.WriteLine(UtilMethods.GetSqlString(DbType.SqlServer,sql,pars))
                };


                //Code First 创建数据库表
                Db.CodeFirst.InitTables(typeof(Admin));
                Db.CodeFirst.InitTables(typeof(Adminrole));
                Db.CodeFirst.InitTables(typeof(Role));
                Db.CodeFirst.InitTables(typeof(Menu));
                Db.CodeFirst.InitTables(typeof(RoleMenu));
                Db.CodeFirst.InitTables(typeof(ProductInfo));
                Db.CodeFirst.InitTables(typeof(ProductType));
                Db.CodeFirst.InitTables(typeof(Market));
                Db.CodeFirst.InitTables(typeof(Handle));
                Db.CodeFirst.InitTables(typeof(StockRemove));
                Db.CodeFirst.InitTables(typeof(ShiftPark));

                #region 仓库
                Db.CodeFirst.InitTables(typeof(Warehouse1));
                Db.CodeFirst.InitTables(typeof(WarehouseType));
                Db.CodeFirst.InitTables(typeof(Location));
                Db.CodeFirst.InitTables(typeof(LocationType));
                #endregion

                #region 采购
                Db.CodeFirst.InitTables(typeof(Procurement));
                Db.CodeFirst.InitTables(typeof(ProcurementReturn));
                Db.CodeFirst.InitTables(typeof(Shopping));
                #endregion

                #region 财务
                Db.CodeFirst.InitTables(typeof(FinanceType));
                Db.CodeFirst.InitTables(typeof(Payable));
                Db.CodeFirst.InitTables(typeof(Receivable));
                Db.CodeFirst.InitTables(typeof(Accounting));
                #endregion
            }
        }
    }
}
